package org.nobject.common.web;

import java.util.Collection;
import java.util.Iterator;
import java.util.Map;

import org.nobject.common.bean.BeanUtils;
import org.nobject.common.lang.CharUtils;
import org.nobject.common.lang.StringUtils;

/**
 * HTML工具类
 *
 * @author bianrongjun
 * @version 1.0
 */
public class HTMLUtils {
	
	/** 文本转HTML */
	public static String text2HTML(String text){
		if(StringUtils.isEmpty(text)) return "";
		return text.replaceAll(" ","&nbsp;").replaceAll("\n", "<br>");
	}
	
	/** genHTMLSelect */
	public static String genHTMLSelect(Collection datas,String textKey,String valueKey,String id,String name,String style){
		StringBuffer sb=new StringBuffer();
		sb.append("<select ");
		if(!StringUtils.isEmpty(id)) sb.append(" id=\""+id+"\" ");
		if(!StringUtils.isEmpty(name)) sb.append(" name=\""+name+"\" ");
		if(!StringUtils.isEmpty(style)) sb.append(" style=\""+style+"\" ");
		sb.append(">");
		
		sb.append("<option value=\"\">请选择</option>");
		if(datas!=null&&datas.size()>=0){
			Object o=datas.iterator().next();
			if(o instanceof Map){
				for (Iterator iterator = datas.iterator(); iterator.hasNext();) {
					Map data = (Map) iterator.next();
					Object t=data.get(valueKey);
					String value=(t==null)?"":t.toString();
					t=data.get(textKey);
					String text=(t==null)?"":t.toString();
					sb.append("<option value=\""+value+"\">"+text+"</option>");
				}
			}else{
				for (Iterator iterator = datas.iterator(); iterator.hasNext();) {
					Object data = iterator.next();
					Object t=null;
					try {
						t = BeanUtils.getProperty(data, valueKey);
					} catch (Exception e) {
						continue;
					}
					String value=(t==null)?"":t.toString();
					try {
						t=BeanUtils.getProperty(data, textKey);
					} catch (Exception e) {
						continue;
					}
					String text=(t==null)?"":t.toString();
					sb.append("<option value=\""+value+"\">"+text+"</option>");
				}
			}
			
		}
		sb.append("</select>");
		return sb.toString();
	}
	
	/** 
	 * 将字符串转化成&#0000转义
	 * @param str 字符串
	 */
	public static String escape(String str){
		char[] cs=CharUtils.toChars(StringUtils.null2Empty(str));
		StringBuffer sb=new StringBuffer();
		for(char c:cs){
			if(c==10){
				sb.append("<br>");
			}else{
				sb.append("&#").append((int)c);	
			}
		}
		return sb.toString();
	}
	
	public static void main(String[] args) {
		String s="实习单位签字（章）";
		System.out.println(escape(s));
	}
}


